<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
 * 
 */

/**
 * Description of speak_service
 *
 * @author Administrator
 */
class Speak_service extends CLI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->library('socket_server');
        $this->load->config('speak',true);
        $this->load->model('unrecognized_model');
    }

    //语言回复服务
    public function service()
    {
        CLI_FUN::echo_system("机器人聊天功能执行 \n");
        $this->socket_server->set_port($this->config->item('speak_service_port','speak')); //传入端口
        $this->socket_server->set_ip($this->config->item('speak_service_ip','speak')); //传入ip
        try{
            $this->socket_server->init();
            do{
                $this->socket_server->accept();
                while($data = $this->socket_server->read())
                {
                    $this->socket_server->write($this->msg($data));
                    if(md5('system$close') == $data)
                    {
                        $close = $this->socket_server->close();
                        if($close == false)
                        {
                                break;
                        }
                    }
                }
            }while (true);
            CLI_FUN::echo_system("机器人聊天功能停止");
        }catch (Exception $e) {
            CLI_FUN::echo_system($e->getMessage());
        }
    }
    
    public function ceshi()
    {
        $this->load->library('socket_client');
        $this->socket_client->set_address($this->config->item('speak_service_ip','speak'));
        $this->socket_client->set_port($this->config->item('speak_service_port','speak'));
        $this->socket_client->set_socket_message(json_encode(array('msg'=>urlencode('speak::close'),'number'=>'13511255367')));
        $data = $this->socket_client->init();
        CLI_FUN::echo_system('服务器返回:'.$data);
    }
    /*
     * 获得回复的内容
     */
    function msg($row)
    {
         $sms_data = json_decode($row);
         if(!is_object($sms_data))
         {
             return false;
         }
         $this->load->library("autoresponders");
         $data = $this->autoresponders->msg(urldecode($sms_data->msg));
         if($data != false)
         {
               return  $data;
         }
         else
         {
               return $this->config->item('speak_msg','speak');
         }
      }
}